# -*- coding: utf-8 -*-
from flask import Blueprint,request,redirect,jsonify
from common.libs.Helper import ops_render,iPagination,getCurrentDate
from common.libs.UrlManager import UrlManager
from common.models.member.Member import Member
from application import app,db


route_member = Blueprint( 'member_page',__name__ )

@route_member.route( "/index" )   # 展示会员列表 实现 搜索，分页功能
def index():
    resp_data = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    query = Member.query   # 数据库查询
    # 搜索  根据内容查询
    if 'mix_kw' in req:
        query = query.filter(Member.nickname.ilike("%{0}%".format(req['mix_kw'])))  # ilike 忽略大小写
    # 搜索  根据状态查询
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(Member.status == int(req['status']))
    # 以下是分页功能
    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'], #
        'page': page,  # 第一页
        'display': app.config['PAGE_DISPLAY'], #
        'url': request.full_path.replace("&p={}".format(page), "")
    }

    pages = iPagination(page_params) # 分页数据
    offset = ( page -1 ) * app.config['PAGE_SIZE'] #偏移量

    list = query.order_by(Member.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()  # 循环数据

    resp_data['list'] = list  # 所以数据
    resp_data['pages'] = pages # 分页
    resp_data['search_con'] = req  #
    resp_data['status_mapping'] = app.config['STATUS_MAPPING']  # 状态
    resp_data['current'] = 'index'
    return ops_render("member/index.html", resp_data)  #第2个参数为给页面的数据


@route_member.route( "/info" )  #  显示个人信息  ，
def info():
    resp_data = {}
    req = request.args  # 获取数据 跟values 一样
    # 根据ID查询个人信息
    id = int(req.get('id',0))

    reback_url = UrlManager.buildUrl("/member/index")
    if id < 1 : # 如果没有ID 返回首页
        return redirect(reback_url)  # redirect 返回首页用

    info = Member.query.filter_by(id = id).first()
    if not info:   # 如果没数据 返回首页
        return redirect(reback_url)

    # 一切正常 返回查询数据
    resp_data['info'] = info
    resp_data['current'] = 'index'
    return ops_render( "member/info.html" ,resp_data)

@route_member.route( "/set" ,methods = ["GET","POST"])  #  两个访问都支持 ，get 展示，post 更改 2018.12.7 编辑功能
def set():
    if request.method == "GET":   # 如果是get   返回数据
        resp_data = {}
        req = request.args
        id = int(req.get('id',0))  #  0 是默认值
        # 以下判断 没有ID 没有数据都返回首页 与info一样
        reback_url = UrlManager.buildUrl("/member/index")
        if id < 1:
            return redirect(reback_url)
        info = Member.query.filter_by(id=id).first()
        if not info:
            return redirect(reback_url)

        if info.status != 1:  # 删除不显
            return redirect(reback_url)

        resp_data['info'] = info #  返回查询到的数据
        resp_data['current'] = 'index'
        return ops_render( "member/set.html",resp_data )
    # post 修改数据  只能修改用户名
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values  # 获取 id 跟修改的名称
    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名~~"
        return jsonify(resp)

    member_info = Member.query.filter_by(id=id).first()  # 查找数据
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "指定会员不存在~~"
        return jsonify(resp)

    member_info.nickname = nickname   # 赋值 提交  姓名与 当前时间
    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()
    return jsonify(resp)


@route_member.route( "/comment" )
def comment():
    return ops_render( "member/comment.html" )





@route_member.route("/ops",methods=["POST"])   ##      2018.12.8   删除 与 恢复   设置status的值即可
def ops():
    resp = { 'code':200,'msg':'操作成功~~','data':{} }
    req = request.values

    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    if not id :
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)

    if act not in [ 'remove','recover' ]:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)

    member_info = Member.query.filter_by( id = id ).first()
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "指定会员不存在~~"
        return jsonify(resp)

    if act == "remove":
        member_info.status = 0
    elif act == "recover":
        member_info.status = 1

    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()
    return jsonify( resp )
